package com.jfzt.config;

import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.message.BasicHeader;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.PostConstruct;
import java.util.Base64;

/**
 * @author: shunpeng.hu
 * @date: 2024/1/4 17:44
 */
//@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Value("${spring.elasticsearch.uris}")
    private String uris;

    @Value("${spring.elasticsearch.username}")
    private String username;

    @Value("${spring.elasticsearch.password}")
    private String password;

    public static String ES_HOSTNAME;

    public static String ES_PORT;

    public static String ES_USERNAME;

    public static String ES_PASSWORD;

    @PostConstruct
    public void es_init() {
        String[] s = uris.split(":");
        ES_HOSTNAME = s[1].split("//")[1];
        ES_PORT = s[2];
        ES_USERNAME = this.username;
        ES_PASSWORD = this.password;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new HttpRequestInterceptior()); // 注册拦截器
    }

    @Bean
    public RestHighLevelClient restHighLevelClient() {
        return new RestHighLevelClient(RestClient.builder(
                new HttpHost(ES_HOSTNAME, Integer.parseInt(ES_PORT), "http"))
                .setDefaultHeaders(new Header[]{new BasicHeader("Authorization",
                        "Basic " + Base64.getEncoder().encodeToString((ES_USERNAME+":"+ES_PASSWORD).getBytes())
                )})
        );
    }
}
